package com.baiyinet.util.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.baiyinet.rest.CustomTrust;
import com.baiyinet.rest.UnSafeHostnameVerifier;
import com.baiyinet.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

/**
 * 图片下载任务
 */
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    private static final String SAVE_PATH = Environment.getExternalStorageDirectory() + "/商品图片/";

    private Context mContext;

    private CustomTrust mCustomTrust;

    private String mHintStr;

    private String mUrl;

    private ProgressDialog mProgressDialog;

    public DownloadImageTask(Context context, String hintStr) {
        this.mContext = context;
        this.mHintStr = hintStr;
        mCustomTrust = new CustomTrust(context);
    }

    /**
     * 表示任务执行之前的操作
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (mProgressDialog == null) {
            // in standard case YourActivity.this
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("下载中…");
            mProgressDialog.show();
        }
    }

    /**
     * 主要是完成耗时的操作
     */
    @Override
    protected Bitmap doInBackground(String... arg0) {
        // 使用网络连接类下载网络数据
        mUrl = arg0[0];
        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS);

            if (!TextUtils.isEmpty(mUrl) && mUrl.startsWith("https")) {
                // 添加https
                httpClientBuilder
                        .sslSocketFactory(mCustomTrust.sslSocketFactory, mCustomTrust.trustManager)
                        .hostnameVerifier(new UnSafeHostnameVerifier());
            }

            OkHttpClient httpClient = httpClientBuilder.build();
            Request request = new Request.Builder().url(mUrl).build();
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                InputStream is = response.body().byteStream();
                return BitmapFactory.decodeStream(is);
            } else {
                Timber.e(response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 主要是更新UI的操作
     */
    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);

        try{
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        }catch(Exception exception){
            exception.printStackTrace();
        }

        String fileExt = null;
        try {
            fileExt = Utils.getFileExtensionFromUrl(Uri.parse(mUrl).getLastPathSegment()).toLowerCase();
        }catch (Exception e) {
            e.printStackTrace();
        }

        String fileName = System.currentTimeMillis() + "";

        saveBitmap(result, fileName + "." + fileExt, fileExt);
    }

    /**
     * 保存方法
     * @param bmp
     **/
    public void saveBitmap(Bitmap bmp, String fileName, String fileExt) {
        File saveFileDir = new File(SAVE_PATH);
        if(!saveFileDir.exists()) {
            saveFileDir.mkdirs();
        }

        File f = new File(SAVE_PATH, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            switch (fileExt) {
                case "jpg":
                case "jpeg":
                    bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    break;
                case "png":
                    bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
                    break;
                default:
                    bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    break;
            }
            out.flush();
            out.close();

            // 发送相册广播
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            mContext.sendBroadcast(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String toastStr = "已将二维码保存到:".concat(SAVE_PATH).concat(fileName);
//        String toastStr = mHintStr.concat(SAVE_PATH).concat(fileName);
        String toastStr = "图片已保存到SD存储卡的\"商品图片\"目录";
        Utils.UI.showToastLong(toastStr);
    }
}
